import { ObjectUtil } from './ObjectUtil';
export const DateUtil = {
	equals: (a, b) => a.getTime() === b.getTime(),
	format: (date, format = 'yyyy-MM-dd HH:mm:ss') => {
		const o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'H+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds()
		};
		if (/(y+)/.test(format)) {
			format = format.replace(
				RegExp.$1,
				String(date.getFullYear()).substr(4 - RegExp.$1.length)
			);
		}
		if (/(S+)/.test(format)) {
			format = format.replace(
				RegExp.$1,
				String('00' + date.getMilliseconds()).substr(-RegExp.$1.length)
			);
		}
		for (const k in o) {
			if (new RegExp('(' + k + ')').test(format)) {
				format = format.replace(
					RegExp.$1,
					RegExp.$1.length === 1
						? o[k]
						: ('00' + o[k]).substr(String(o[k]).length)
				);
			}
		}
		return format;
	},
	time: date => {
		const target = new Date(Date.parse(date));
		if (isNaN(target.getTime())) {
			throw new Error('无法将该字符串转化为时间');
		} else {
			return target;
		}
	},
	formatObject: (o, keys, format = 'yyyy-MM-dd HH:mm:ss') => {
		const clone = ObjectUtil.clone(o);
		for (const key of keys) {
			const val = o[key];
			if (val instanceof Date) {
				clone[key] = DateUtil.format(val, format);
			}
		}
		return clone;
	},
	timeObject: (o, keys) => {
		const clone = ObjectUtil.clone(o);
		for (const key of keys) {
			const val = o[key];
			if (typeof val === 'string') {
				clone[key] = DateUtil.time(val);
			}
		}
		return clone;
	}
};
